package cn.mothin.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.dao.SystemUserDao;
import cn.mothin.dictionary.SystemUserState;
import cn.mothin.entity.SystemUser;
import cn.mothin.frame.bean.LoginUser;
import cn.mothin.frame.core.base.BaseService;
import cn.mothin.frame.help.Password;
import cn.mothin.frame.help.UniqueCode;
import cn.mothin.frame.util.ObjectUtil;
import cn.mothin.frame.util.StringUtil;
import cn.mothin.vo.LoginForm;

@Service("53ffd6697b0bf81ac00a9817")
public class LoginService extends BaseService {
    @Autowired
    private SystemUserDao systemUserDao;

    public Object authentication(LoginForm form, String random, String ip) {
        if (random == null || !random.equals(form.getRandom())) {
            return null;
        }

        List<SystemUser> list = systemUserDao.findSystemUsersByAccount(form
                .getAccount());
        if (list.size() > 0) {
            for (SystemUser systemUser : list) {
                if (Password.equals(form.getPassword(),
                        systemUser.getPassword(), random)) {
                    if (StringUtil.isNullOrEmpty(systemUser.getState())) {
                        return "状态异常，请与相关负责人联系...";
                    }
                    if (systemUser.getState().equals(
                            SystemUserState.NORMAL.getId())) {
                        return new LoginUser(systemUser.getId(),
                                systemUser.getName(), UniqueCode.make(), ip,
                                systemUser.isSuperUser());
                    } else if (systemUser.getState().equals(
                            SystemUserState.APPLY.getId())) {
                        return "注册申请正在审批中，请耐心等候...";
                    } else {
                        return "状态异常，请与相关负责人联系...";
                    }
                }
            }
        }
        return null;
    }

    public boolean addUser(LoginForm loginForm) {
        String sql = "SELECT COUNT(id) FROM system_user WHERE account=? AND deleted<>TRUE";
        Long l = sqlHelper.queryCount(sql, loginForm.getSystemUser()
                .getAccount());
        if (l > 0) {
            return false;
        }
        SystemUser systemUser = new SystemUser();
        ObjectUtil.SyncObjectsWithFields(systemUser, loginForm.getSystemUser(),
                SystemUser.NAME, SystemUser.ACCOUNT, SystemUser.MOBILE,
                SystemUser.EMAIL);
        systemUser.setState(SystemUserState.APPLY.getId());
        systemUser.setId(UniqueCode.make());
        systemUser.setPassword(loginForm.getSystemUser().getPassword());
        systemUserDao.save(systemUser);
        return true;
    }
}
